package com.junqson.je.msg.service;

import com.junqson.je.msg.model.MessageModel;
import com.junqson.je.msg.repo.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Descriptions 站内信crud相关操作
 * @Company
 * @Author Junqson
 * @Date 2020/2/10 18:00
 * @Version 1.0
 */
@Service
public class MsgCrudService {

    @Autowired
    private MessageRepo repo;

    @Resource
    private WebSocketService webSocketService;

    public List<MessageModel> findByToId(Integer toId) {
        return repo.findByToIdOrderByCreateTimeDesc(toId);
    }

    public List<MessageModel> findByFromId(Integer fromId) {
        return repo.findByFromId(fromId);
    }

    public MessageModel save(MessageModel model) {
        MessageModel mm = repo.save(model);
        sendCount(model.getToId());
        return mm;
    }

    /**
     * 查找未读通知的数量
     **/
    public List<MessageModel> findNotRead(Integer userId) {
        return repo.findByToIdAndReadState(userId, false);
    }

    public void read(Long id, Integer userId) {
        repo.read(id, userId);
        int count = findNotRead(userId).size();
        webSocketService.messageBroadcast(userId, String.valueOf(count));
//        pushClient.sendMessage(userId, String.valueOf(count));
    }

    // 发送未读消息数目
    public void sendCount(Integer userId) {
        int count = findNotRead(userId).size();
        webSocketService.messageBroadcast(userId, String.valueOf(count));
//        pushClient.sendMessage(userId, String.valueOf(count));
    }
}
